package other.xsy.passlys.receivable;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.service.XoqlService;
import other.xsy.passlys.util.HCXObjectService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 认领审批通过回写booking、应收
 * @Author 黎炎松
 * 2024-08-07 14:13
 */
public class ClaimCompleteAfter implements ApprovalEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "应收审批通过 ==> ";



    public static void main(String[] args) {
        ClaimCompleteAfter claimCompleteAfter = new ClaimCompleteAfter();
        ApprovalEventRequest approvalEventRequest = new ApprovalEventRequest();
        approvalEventRequest.setDataId(3414524994607762L);
        claimCompleteAfter.execute(approvalEventRequest);
    }

    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) {
        logger.info(LOGGER_MSG + "触发开始");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());

        try {
            Long claimId = request.getDataId();

            // 查询认领下的开票明细数据,获取 bookingids
            String sql = "select id,booking__c from claimDetails__c where claim__c = " + claimId;
            List<ClaimDetails__c> claimDetailList = hcxObjectService.query(sql, ClaimDetails__c.class);
            List<Long> bookingIds = claimDetailList.stream().map(v -> v.getBooking__c()).collect(Collectors.toList());

            // 延迟2s (xoql有延迟问题)
            Thread.sleep(2000);

            // 修改认领金额字段
            ReceivableService receivableService = new ReceivableService();
            receivableService.calcClaimAmounByBooking(bookingIds);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }


}
